<?php
use \think\exception\HttpResponseException;
// 应用公共文件
function ajax($data = [], $code = 1, $message = '', $header = [])
{
    $ret = [
        'message' => config('code.' . $code),
        'code' => $code,
        'data' => $data,
    ];
    if($message) {
        $ret['message'] = $message;
    }
    if (config('app_debug')) {
        $ret['cmd'] = request()->controller() . '/' . request()->action();
    }
    return json($ret);
}


function checkPost($postArray) {
    if(empty($postArray)) {
        throw new HttpResponseException(ajax($postArray,-2,"参数不能为空"));
    }
    foreach ($postArray as $value) {
        if (is_null($value) || $value === '') {
            throw new HttpResponseException(ajax($postArray,-2,"参数不能为空"));
        }
    }
    return true;
}

//日志
function mylog($cmd,$str,$filename='common.log') {
    $file= LOG_PATH . '/' . $filename;
    create_dir($file);
    $text='[Time ' . date('Y-m-d H:i:s') ."]\ncmd:" .$cmd. "\n" .$str. "\n---END---" . "\n";
    if(false !== fopen($file,'a+')){
        file_put_contents($file,$text,FILE_APPEND);
    }else{
        echo '创建失败';
    }
}

function create_dir($file_path = '') {
    $position =  strripos($file_path,'/');
    $dirname = substr($file_path,0,$position);
    if(!$dirname) {
        exit(json_encode(['msg'=>'invalid directory']));
    }
    if(!is_dir($dirname)) {
        @mkdir($dirname,0755,true);
    }
}

function pp($info) {
    echo '<pre>';
    print_r($info);
    echo '</pre>';
}



function randomkeys($length) {
    $returnStr='';
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    for($i = 0; $i < $length; $i ++) {
        $returnStr .= $pattern [mt_rand ( 0, 61 )];
    }
    return $returnStr;
}

function randname($length) {
    $returnStr='';
    $pattern = 'abcdefghijklmnopqrstuvwxyz';
    for($i = 0; $i < $length; $i ++) {
        $returnStr .= $pattern [mt_rand ( 0, 25 )];
    }
    return $returnStr;
}

function gen_unique_number($letter = '')
{
    $time = explode (" ", microtime ());
    $timeArr = explode('.',$time [0]);
    $mtime = array_pop($timeArr);
    $fulltime = $letter.$time[1].$mtime;
    return $fulltime;
}

function create_unique_number($letter = '') {
    $time = explode (" ", microtime ());
    $timeArr = explode('.',$time [0]);
    $mtime = array_pop($timeArr);
    $fulltime = $letter.$time[1].$mtime . mt_rand(100,999);
    return $fulltime;
}

//接口上传图片
function upload_file($key,$allowType = [],$maxsize=512) {

    if ($_FILES[$key]["error"] > 0) {
        throw new HttpResponseException(ajax("error: " . $_FILES[$key]["error"],-1));
    }
    if($_FILES[$key]["type"] == '') {
        throw new HttpResponseException(ajax('文件存在中文名或超过2G',5));
    }
    if(!in_array($_FILES[$key]["type"],$allowType)) {
        throw new HttpResponseException(ajax('文件类型不符' . $_FILES[$key]["type"],5));
    }
    if($_FILES[$key]["size"] > $maxsize*1024) {
        throw new HttpResponseException(ajax('文件大小不超过'.(round($maxsize/1024,2)).'M',5));
    }

    $filename_array = explode('/',$_FILES[$key]['type']);
    $ext = array_pop($filename_array);
    $path =  'tmp/';
    is_dir($path) or mkdir($path,0755,true);
    //转移临时文件
    $new_name = create_unique_number() . '.' . $ext;
    move_uploaded_file($_FILES[$key]["tmp_name"], $path . $new_name);
    return [
        'name' => $_FILES[$key]['name'],
        'url' => $path . $new_name,
    ];

}

function move_file_to_directory($from_obj,$to_path) {
    $arr = explode('/',$from_obj);
    $to_obj = $to_path . end($arr);
    //如果一样不需要挪动
    if($from_obj !== $to_obj) {
        create_dir($to_obj);
        rename($from_obj, $to_obj);
    }
    return [
        'code' => 0,
        'path' => $to_obj
    ];

}

// 验证密码, 必须同时包含大小写字母,数字, 特殊字符
function validate_password($password, $min_length=8) {
    $pattern = '/^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{'.$min_length.',32}$/';
    if (preg_match($pattern, $password)) {
        return true;
    }
    return false;
}

// 至少包含三种
function validate_password_v2($password, $min_length=8) {
    $score = 0;
    if (preg_match('/(?=.*[a-z])/', $password)) {
        $score++;
    }
    if (preg_match('/(?=.*[A-Z])/', $password)) {
        $score++;
    }
    if (preg_match('/(?=.*\d)/', $password)) {
        $score++;
    }
    if (preg_match('/(?=.*[^\da-zA-Z])/', $password)) {
        $score++;
    }
    if (!preg_match('/^.{'.$min_length.',}$/', $password)) {
        return false;
    }
    if ($score >= 3) {
        return true;
    }
    return false;
}